/**
 * 图形验证码
 */
const { BadRequest } = require("http-errors");
const { failure } = require("../utils/responses");
const { getKey } = require("../utils/redis");

module.exports = async (req, res, next) => {
  try {
    const { captchaKey, captchaText, type } = req.body;
    console.log("type====", type);
    if (type && type == 1) {
      next();
    } else {
      // 判断验证码为空
      if (!captchaText) {
        throw new BadRequest("验证码不能为空。");
      }

      // 从 Redis 获取验证码的值
      const captcha = await getKey(captchaKey);
      console.log("captcha", captcha);
      if (!captcha) {
        throw new BadRequest("验证码已过期。");
      }

      // 比对验证码，忽略大小写
      if (captcha.toLowerCase() !== captchaText.toLowerCase()) {
        throw new BadRequest("验证码不正确。");
      }

      next();
    }
  } catch (error) {
    failure(req, res, error);
  }
};
